package com.ruoyi.mp.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.mp.api.domain.MpAccount;
import com.ruoyi.mp.domain.MpTag;
import com.ruoyi.mp.mapper.MpTagMapper;
import com.ruoyi.mp.service.IMpAccountService;
import com.ruoyi.mp.service.IMpTagService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 公众号标签Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-18
 */
@Service
public class MpTagServiceImpl implements IMpTagService
{
    @Autowired
    private MpTagMapper mpTagMapper;
    @Autowired
    private WxMpService wxService;
    @Autowired
    private IMpAccountService iMpAccountService;

    private static final Logger log = LoggerFactory.getLogger(MpTagServiceImpl.class);
    /**
     * 查询公众号标签
     *
     * @param id 公众号标签主键
     * @return 公众号标签
     */
    @Override
    public MpTag selectMpTagById(Long id)
    {
        return mpTagMapper.selectMpTagById(id);
    }

    /**
     * 查询公众号标签列表
     *
     * @param mpTag 公众号标签
     * @return 公众号标签
     */
    @Override
    public List<MpTag> selectMpTagList(MpTag mpTag)
    {
        return mpTagMapper.selectMpTagList(mpTag);
    }

    /**
     * 新增公众号标签
     *
     * @param mpTag 公众号标签
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertMpTag(MpTag mpTag) throws WxErrorException {
        // 空值检查
        MpAccount mpAccount = iMpAccountService.selectMpAccountById(mpTag.getAccountId());
        if (mpAccount == null) {
            throw new IllegalArgumentException("Invalid account ID");
        }
        // 设置 appId
        mpTag.setAppId(mpAccount.getAppId());
        // 设置 creator
        mpTag.setCreateBy(String.valueOf(SecurityUtils.getUsername()));
        try {

            // 创建标签
            WxUserTag wxUserTag = wxService.switchoverTo(mpAccount.getAppId()).getUserTagService().tagCreate(mpTag.getName());
            mpTag.setCreateTime(DateUtils.getNowDate());
            mpTag.setTagId(wxUserTag.getId());
        } catch (WxErrorException e) {
            log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
            throw e;
        }
        catch (Exception e) {
            log.error("Error creating tag: {}", e.getMessage(), e);
            throw new WxErrorException(e);
        }
        // 插入数据库
        return mpTagMapper.insertMpTag(mpTag);
    }

    /**
     * 修改公众号标签
     *
     * @param mpTag 公众号标签
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMpTag(MpTag mpTag) throws WxErrorException {
        final int NOT_DELETED = 0; // 常量定义
        mpTag.setDeleted(NOT_DELETED);
        mpTag.setUpdateTime(DateUtils.getNowDate());

        try {
                MpAccount mpAccount = iMpAccountService.selectMpAccountById(mpTag.getAccountId());
                if (mpAccount != null) { // 避免空指针异常
                    mpTag.setAppId(mpAccount.getAppId());
                    mpTag.setCreateBy(String.valueOf(SecurityUtils.getUsername())); // 确保 userId 的有效性
                    wxService.switchoverTo(mpAccount.getAppId()).getUserTagService().tagUpdate(mpTag.getTagId(), mpTag.getName());
                } else {
                    throw new IllegalStateException("未能找到对应的公众号账户");
                }
            return mpTagMapper.updateMpTag(mpTag);
        }catch (WxErrorException e) {
            log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
            throw e;
        }
        catch (Exception e) {
            // 异常处理
            throw new WxErrorException(e);
        }
    }

    /**
     * 批量删除公众号标签
     *
     * @param ids 需要删除的公众号标签主键
     * @return 结果
     */
    /**
     * 批量删除公众号标签
     *
     * @param ids 需要删除的公众号标签主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteMpTagByIds(Long[] ids) throws WxErrorException {
        // 检查 ids 是否为空或长度为0
        if (ids == null || ids.length == 0) {
            log.warn("Ids array is empty or null.");
            return 0;
        }
            try {

                for (Long id : ids) {
                    MpTag mpTag = this.mpTagMapper.selectMpTagById(id);
                    String appId = iMpAccountService.selectMpAccountById(mpTag.getAccountId()).getAppId();
                    wxService.switchoverTo(appId).getUserTagService().tagDelete(mpTag.getTagId());
                }
                // 删除数据库记录
                return  mpTagMapper.deleteMpTagByIds(ids);
            }catch (WxErrorException e) {
                log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
                throw e;
            }
            catch (Exception e) {
                log.error("Failed to delete tag from remote service: {}", e.getMessage(), e);
                throw new WxErrorException(e);
            }
    }


    /**
     * 删除公众号标签信息
     *
     * @param id 公众号标签主键
     * @return 结果
     */
    @Override
    public int deleteMpTagById(Long id)
    {
        return mpTagMapper.deleteMpTagById(id);
    }

    /**
     * 同步更新标签
     *
     * @param mpTags
     * @return 结果
     */
    @Override
    public int insertMpTagList(List<MpTag> mpTags){
        for(MpTag mpTag : mpTags){
            this.mpTagMapper.insertMpTag(mpTag);
        }
        return 1;
    }

    /**
     * 删除某一个公众号下的标签
     * @param accountId
     * @return
     */
    @Override
    public int deleteTagsByAccountId(Long accountId){
        return this.mpTagMapper.deleteTagsByAccountId(accountId);
    }

    @Override
    public int tagUserlist(Long ids) {
        return  this.mpTagMapper.deleteTagsByAccountId(ids);
    }

    @Override
    public List<MpTag> selectAllMpTagList(String appid) {
        return  this.mpTagMapper.selectAllMpTagList(appid);
    }

}
